package com.magicalcoder.youyaboot.javafx;
/**
 * 这个别往linux里发布 因为linux 不含javafx包 所以加上就报错了
 */

import com.magicalcoder.lowcode.core.common.file.FileHelper;
import com.magicalcoder.lowcode.core.utils.StringUtil;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class InitDbApplication extends Application {

    private static String resourcePath;
    @Override
    public void start(Stage primaryStage) throws Exception {

        GridPane grid = new GridPane();
        grid.setAlignment(Pos.CENTER);
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(25, 25, 25, 25));
        ColumnConstraints column1 = new ColumnConstraints(100);
        ColumnConstraints column2 = new ColumnConstraints(50, 150, 300);
        column2.setHgrow(Priority.ALWAYS);
        grid.getColumnConstraints().addAll(column1, column2);
//更多请阅读：https://www.yiibai.com/javafx/javafx_gridpane.html


        int start=0;
 /*       Text scenetitle = new Text("欢迎使用");
        scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
        grid.add(scenetitle, 0, 0, 2, 1);

*/
        Label dbTypeLabel = new Label("数据库:");
        grid.add(dbTypeLabel, 0, start);

        ComboBox dbTypeComboBox = new ComboBox();
        dbTypeComboBox.getItems().addAll(
                "sqlite","mysql","sqlserver","联系我们..."
        );
        grid.add(dbTypeComboBox, 1, start);

        Label ip = new Label("IP:");
        grid.add(ip, 0, ++start,5,1);

        TextField ipTextField = new TextField();
        grid.add(ipTextField, 1, start);

        Label port = new Label("端口:");
        grid.add(port, 0, ++start);

        TextField portTextField = new TextField();
        grid.add(portTextField, 1, start);

        Label db = new Label("数据库名:");
        grid.add(db, 0, ++start);

        TextField dbTextField = new TextField();
        grid.add(dbTextField, 1, start);

        Label url = new Label("自定义url可不填:");
        grid.add(url, 0, ++start);

        TextField urlTextField = new TextField();
        grid.add(urlTextField, 1, start);

        Label userName = new Label("用户名:");
        grid.add(userName, 0, ++start);

        TextField userTextField = new TextField();
        grid.add(userTextField, 1, start);

        Label pw = new Label("密码:");
        grid.add(pw, 0, ++start);

        PasswordField pwField = new PasswordField();
        grid.add(pwField, 1, start);

        Button btn = new Button("修改");
        HBox hbBtn = new HBox(10);
        hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
        hbBtn.getChildren().add(btn);
        grid.add(hbBtn, 1, ++start);

        // 将pane加入到Scen中
        Scene scene = new Scene(grid, 500, 300);


        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                resourcePath = resourcePath();
                if(dbTypeComboBox.getValue()==null){
                    new Alert(Alert.AlertType.INFORMATION,"请选择您的数据库").showAndWait();
                    return;
                }
                String dbType = dbTypeComboBox.getValue().toString();
                if(StringUtil.isBlank(dbType)){
                    return;
                }
                if(dbType.contains("联系我们")){
                    new Alert(Alert.AlertType.INFORMATION,"其他数据库可联系管理员QQ:799374340").showAndWait();
                    return;
                }
                boolean success = replaceApplicationYml(dbType);
                success = success && replaceYml(dbType,ipTextField.getText(),portTextField.getText(),dbTextField.getText(),userTextField.getText(),pwField.getText(),urlTextField.getText());
                if(success){
                    new Alert(Alert.AlertType.INFORMATION,"配置成功，关闭本窗口重新启动即可").showAndWait();
                }
            }
        });
        // 设置stage的scen，然后显示我们的stage
        primaryStage.setScene(scene);
        primaryStage.setTitle("配置数据库");
        primaryStage.show();
    }

    private boolean replaceYml(String dbType,String ip,String port,String dbName,String userName,String password,String url){
        if("sqlite".equals(dbType)){
            return true;
        }
        ip = ip.trim();
        port = port.trim();
        dbName = dbName.trim();
        userName = userName.trim();
        password = password.trim();
        url = url.trim();
        if(StringUtil.isBlank(url)){
            if(StringUtil.isBlank(ip)){
                new Alert(Alert.AlertType.INFORMATION,"请填写IP").showAndWait();
                return false;
            }
            if(StringUtil.isBlank(ip)){
                new Alert(Alert.AlertType.INFORMATION,"请填写端口").showAndWait();
                return false;
            }
            if(StringUtil.isBlank(ip)){
                new Alert(Alert.AlertType.INFORMATION,"请填写数据库名").showAndWait();
                return false;
            }
        }
        String file = resourcePath+"application-"+dbType+".yml";
        if("mysql".equals(dbType)){
            if(StringUtil.isNotBlank(url)){
                replaceFileReg(file,"\\s+url:\\s+(.*)",url);
            }else {
                replaceFileReg(file,"jdbc:mysql://(.*)\\?",ip+":"+port+"/"+dbName);
            }
        }else if("sqlserver".equals(dbType)){
            if(StringUtil.isNotBlank(url)){
                replaceFileReg(file,"\\s+url:\\s+(.*)",url);
            }else {
                replaceFileReg(file,"jdbc:sqlserver://(.*)",ip+":"+port+";DataBaseName="+dbName);
            }
        }else {
            return false;
        }
        replaceFileReg(file,"\\s+username:\\s+(.*)",userName);
        replaceFileReg(file,"\\s+password:\\s+(.*)",password);
        return true;
    }

    private String resourcePath(){
        String path = InitDbApplication.class.getResource("/").getPath();
        if(path.startsWith("file:")){
            path = path.substring(5);
        }
        System.out.println("工作目录"+path);
        String workspace = path.split("/youyaboot/")[0];
        return workspace+"/youyaboot/src/main/resources/";
    }
    private boolean replaceApplicationYml(String dbType){
        String file = resourcePath+"application.yml";
        replaceFileReg(file,"\\s+active:\\s+(.*)",dbType);
        return true;
    }
    //查找替换 
    private static void replaceFileReg(String targetFile,String reg,String replace){
//        String youyaboot = "youyaboot";
//        String youyapi = "youyapi";
        replaceFile(targetFile,reg,replace);
//        replaceFile(targetFile.replace(youyaboot,youyapi),reg,replace);
    }
    private static void replaceFile(String targetFile,String reg,String replace){
        System.out.println(targetFile);
        String content = FileHelper.fastReadAllLineFile(new File(targetFile),"UTF-8");
        if(content==null){
            System.out.println("未找到application.yml");
            return ;
        }
        StringBuffer sb = new StringBuffer() ;
        Pattern p = Pattern.compile(reg) ;
        Matcher m = p.matcher(content) ;
        while( m.find() ){
            String group1 = m.group(1);
            String line = m.group();
            line = line.replace(group1,replace);
            //替换掉查找到的字符串 \\ $必须替换下 否则报错
            m.appendReplacement(sb, line) ;
        }
        //别忘了加上最后一点
        m.appendTail(sb) ;
        FileHelper.fastWriteFileUTF8(targetFile,sb.toString());
    }

    public static void configDb(String[] args) {
        launch(args);
    }
}
